package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderAdminMapper;
import com.sky.mapper.OrderDetaliMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderAdminService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderAdminServiceImpl implements OrderAdminService {

    private static final Logger log = LoggerFactory.getLogger(OrderAdminServiceImpl.class);
    @Autowired
    private OrderAdminMapper orderAdminMapper;
    @Autowired
    private OrderDetaliMapper orderDetailMapper;


    /**
     * 订单搜索
     * @param dto
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO dto) {

        //设置分页参数
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        Page<Orders> pageInfo = orderAdminMapper.page(dto);

        //第二个返回对象
        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (pageInfo != null && pageInfo.getTotal() > 0) {
            for (Orders orders : pageInfo) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(pageInfo.getTotal(), list);

    }

    /**
     * 统计订单数据
     * @return
     */
    @Override
    @ApiOperation("订单统计")
    public OrderStatisticsVO statistics() {
        //构造返回对象
        OrderStatisticsVO vo = new OrderStatisticsVO();
        vo.setToBeConfirmed(0);
        vo.setConfirmed(0);
        vo.setDeliveryInProgress(0);

        //1.查询所有订单状态
        List<Integer> statusList = orderAdminMapper.statusList();
        log.info("订单状态{}",statusList);
        //2.遍历订单状态，查询订单数量
        statusList.forEach(status -> {
            if(status.equals(Orders.TO_BE_CONFIRMED)){
                vo.setToBeConfirmed(vo.getToBeConfirmed() + 1);
            }else if(status.equals(Orders.CONFIRMED)){
                vo.setConfirmed(vo.getConfirmed() + 1);
            }else if(status.equals(Orders.DELIVERY_IN_PROGRESS)){
                vo.setDeliveryInProgress(vo.getDeliveryInProgress() + 1);
            }
        });

        //3.返回结果
        log.info("订单统计结果{}",vo);
        return vo;
    }

    /**
     * 订单详情
     * @param id
     */
    @Override
    public OrderVO orderDetail(Long id) {
        //创建订单VO对象
        OrderVO orderVO = new OrderVO();

        //1.查询订单信息
        Orders orders = orderAdminMapper.selectById(id);
        BeanUtils.copyProperties(orders, orderVO);
        log.info("查询到的订单信息：{},订单号：{}", orders,orders.getId());

        //2.查询订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        //订单详情可能有多个值，循环赋值给orderVO
        orderVO.setOrderDetailList(orderDetailList);

        log.info("查询出来的订单详情：{}",orderVO);


        return orderVO;

    }

    /**
     * 接单
     * @return
     */
    @Override
    public void confirm(OrdersConfirmDTO dto) {
        Orders orders = Orders.builder()
                .id(dto.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderAdminMapper.update(orders);
    }

    /**
     * 拒单
     * @param dto
     */
    @Override
    public void reject(OrdersRejectionDTO dto) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderAdminMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderAdminMapper.selectById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            ordersDB.setPayStatus(2);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orders.setPayStatus(ordersDB.getPayStatus());
        log.info( "更新订单：{}", orders);
        orderAdminMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderAdminMapper.selectById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderAdminMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderAdminMapper.selectById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderAdminMapper.update(orders);
    }

}
